package com.brush.web.app.login;

import com.brush.common.constant.CacheConstants;
import com.brush.common.core.controller.BaseController;
import com.brush.common.core.domain.R;
import com.brush.common.core.domain.req.AppLoginReq;
import com.brush.common.core.domain.resp.AppUserDetails;
import com.brush.common.utils.SecurityUtils;
import com.brush.framework.web.service.AppLoginService;
import com.brush.web.app.login.req.SmsReq;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;


@Api(tags = "app-登录管理")
@RestController
@RequestMapping("/app")
public class AppLoginController extends BaseController {

    @Autowired
    private AppLoginService appLoginService;

    @Autowired
    private RedisTemplate redisTemplate;



    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public R<String> login(@Valid @RequestBody AppLoginReq req){
        String token=this.appLoginService.login(req);
        return R.ok(token);
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @ApiOperation(value = "获取用户信息")
    @GetMapping("getInfo")
    public R<AppUserDetails> getInfo()  {
        // 获取用户信息
        AppUserDetails loginUser = SecurityUtils.getAppLoginUser();

        return R.ok(loginUser);
    }


    /**
     * 发送验证码
     * @return
     */
    @ApiOperation(value = "发送短信验证码")
    @PostMapping("/sendSms")
    public R<Map<String,Object>> sendSms(@RequestBody @Valid SmsReq req){
        //1、判断redis是否存在验证码，如果存在，则提示用户已发送过验证码，请勿重复发送
        String redisKey="";
        if(req.getType()==1){
            redisKey= CacheConstants.SMS_LOGIN_CODE_KEY+req.getPhone();
        }else {
            redisKey=CacheConstants.SMS_REGISTER_CODE_KEY+req.getPhone();
        }

        if(redisTemplate.hasKey(redisKey)){
            return R.fail("请勿重复发送验证码");
        }
        int expireTime=2;

        String code= new Random().nextInt(9000)+1000+"";

        //调用 云短信发送的功能

        this.redisTemplate.opsForValue().set(redisKey,code, expireTime, TimeUnit.MINUTES);


        Map<String,Object> result=new HashMap<>();
        result.put("expired", expireTime*60);

        return R.ok(result);
    }
}
